from django.http import JsonResponse
import jwt
from django.conf import settings
from user.models import User


def login_check(fn):
    def wrap(request, *args, **kwargs):
        # 获取token
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            result = {'code': 403, 'error': '请登录'}
            return JsonResponse(result)
        # 2 校验token
        try:
            payload = jwt.decode(token, settings.JWT_TOKEN_KEY)
        except:
            result = {'code': 403, 'error': '请登录'}
            return JsonResponse(result)
        # 3 从payload获取用户ID
        userid = payload['userid']
        user = User.objects.get(id=userid)
        # 4 将用户对象以附加数据的方式保存到request对象中
        request.myuser = user
        # 5 调用装饰器修饰的函数
        return fn(request, *args, **kwargs)

    return wrap


def get_user_by_token(token):
    # 游客
    if not token:
        return None
    try:
        payload = jwt.decode(token, settings.JWT_TOKEN_KEY)
    except:
        # 也当成游客
        return None
    userid = payload['userid']
    try:
        user = User.objects.get(id=userid)
    except:
        return None
    return user


def get_user_by_request(request):
    # 获取token
    token = request.META.get('HTTP_AUTHORIZATION')
    user = get_user_by_token(token)
    return user
